package org.luckystrophe.snowtoms.listener;

import org.luckystrophe.snowtoms.R;
import org.luckystrophe.snowtoms.fragment.INFOFragment_;
import org.luckystrophe.snowtoms.fragment.RankFragment_;
import org.luckystrophe.snowtoms.fragment.SNSFragment_;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;

public class SnowTomsTabListener<T extends Fragment> implements ActionBar.TabListener {

	private SherlockFragment mFragment;
	private final SherlockFragmentActivity mActivity;
	private final String mTag;
	private final Class<T> mClass;

	public SnowTomsTabListener(SherlockFragmentActivity mainActivity, String tag, Class<T> _mClass) {
		mActivity = mainActivity;
		mTag = tag;
		mClass = _mClass;
	}

	@Override
	public void onTabSelected(Tab tab, FragmentTransaction ft) {
		SherlockFragment preInitializedFragment = (SherlockFragment) mActivity.getSupportFragmentManager()
				.findFragmentByTag(mTag);

		if (preInitializedFragment == null) {
			mFragment = (SherlockFragment) SherlockFragment.instantiate(mActivity, mClass.getName());
			ft.add(android.R.id.content, mFragment, mTag);

		} else {
			ft.attach(preInitializedFragment);
		}

		if (mClass.getName().toString() == RankFragment_.class.getName().toString()) {
			tab.setIcon(R.drawable.tab_icon_ranking2);

		} else if (mClass.getName().toString() == SNSFragment_.class.getName().toString()) {
			tab.setIcon(R.drawable.tab_icon_sns2);

		} else if (mClass.getName().toString() == INFOFragment_.class.getName().toString()) {
			tab.setIcon(R.drawable.tab_icon_location2);
		}

	}

	@Override
	public void onTabUnselected(Tab tab, FragmentTransaction ft) {

		SherlockFragment preInitializedFragment = (SherlockFragment) mActivity.getSupportFragmentManager()
				.findFragmentByTag(mTag);

		if (preInitializedFragment != null) {
			ft.detach(preInitializedFragment);
		} else if (mFragment != null) {
			ft.detach(mFragment);
		}

		if (mClass.getName().toString() == RankFragment_.class.getName().toString()) {
			tab.setIcon(R.drawable.tab_icon_ranking1);

		} else if (mClass.getName().toString() == SNSFragment_.class.getName().toString()) {
			tab.setIcon(R.drawable.tab_icon_sns1);

		} else if (mClass.getName().toString() == INFOFragment_.class.getName().toString()) {
			tab.setIcon(R.drawable.tab_icon_location1);
		}
	}

	@Override
	public void onTabReselected(Tab tab, FragmentTransaction ft) {
		if (tab.getTag().equals("SNS")) {
		}
	}

}
